package com.gmzg.gmzgnews.live.view;


import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.gmzg.gmzgnews.R;
import com.gmzg.gmzgnews.live.adapter.LiveFragmentAdapter;
import com.gmzg.gmzgnews.live.adapter.PicturePageAdapter;
import com.gmzg.gmzgnews.live.cache.GetDataCache;
import com.gmzg.gmzgnews.live.cache.LiveHotInterceptor;
import com.gmzg.gmzgnews.live.cache.NetworkUtil;
import com.gmzg.gmzgnews.live.model.LiveModel;
import com.gmzg.gmzgnews.live.services.LiveHotService;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Cache;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;
import rx.Observable;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * A simple {@link Fragment} subclass.
 */
public class HotTopFragmentWithCache extends BaseFragment implements IHotTopFragmentWithCache, SwipeRefreshLayout.OnRefreshListener {

    ArrayList<LiveModel.Data.DataBean> mItems;
    LiveFragmentAdapter mAdapter;
    private int currentIndex = 1500;

    private Handler mHandler = new Handler();

    @BindView(R.id.hot_list)
    RecyclerView mHotList;
    @BindView(R.id.swipeRefreshLayout)
    SwipeRefreshLayout mSwipeRefreshLayout;
    private LiveHotService mLiveHotService;
    private GetDataCache mFile;
    private Cache mCache;
    private LiveHotInterceptor mInterceptor;
    private boolean mAccess2Net;
    public static final int DEFAULT_TIMEOUT = 5000;


    public HotTopFragmentWithCache() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Log.d("ddddddddd", "onCreate: ");
//        注册EventBus事件,接受点击时传过来的对象
        EventBus.getDefault().register(this);
        mItems = new ArrayList<>();

        initCache();
        initRetrofitService();


    }

    private void initCache() {
        mFile = new GetDataCache(getContext());
        mCache = mFile.getCache();
        mInterceptor = new LiveHotInterceptor(getContext());
        mAccess2Net = mInterceptor.getAccess2Net();
    }

    private void initRetrofitService() {
        //retrofit底层用的okHttp,所以设置超时还需要okHttp
        //包括设置缓存
        //然后设置5秒超时
        //TimeUnit为java.util.concurrent包下的时间单位
        //TimeUnit.SECONDS这里为秒的单位
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                .writeTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                .readTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                .cache(mCache)
                .addInterceptor(mInterceptor)
                .build();

        Retrofit.Builder builder = new Retrofit.Builder();
        Retrofit retrofit = builder.baseUrl("http://ic.snssdk.com/")
                .addConverterFactory(ScalarsConverterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.createWithScheduler(Schedulers.io()))
                .client(client)
                .build();
        mLiveHotService = retrofit.create(LiveHotService.class);
    }


    @Override
    public void onResume() {
        super.onResume();
        Log.d("ddddddddd", "onResume: ");

//        //启动广告轮播线程
//        Thread thread = new Thread(this);
//        thread.start();

    }

    //检查网络
    private boolean checkNet() {
        if (NetworkUtil.isNetworkAvailable(getContext())) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public String getFragmentTitle() {
        return "热门";
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        Log.d("ddddddddd", "onAttach: ");
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View ret = inflater.inflate(R.layout.fragment_hot_top, container, false);
        ButterKnife.bind(this, ret);
        Log.d("ddddddddd", "onCreateView: ");

        //添加刷新监听事件
        mSwipeRefreshLayout.setOnRefreshListener(this);

        if (mHotList != null) {
            //布局管理器，能够对Item进行排版
            RecyclerView.LayoutManager lm =
                    new LinearLayoutManager(
                            getContext(),
                            LinearLayoutManager.VERTICAL,
                            false);

            mHotList.setLayoutManager(lm);

        }

        mAdapter = new LiveFragmentAdapter(getContext(), mItems, mHotList);
//        View headView= LayoutInflater.from(getContext()).inflate(R.layout.live_hot_headview,mHotList,false);


        //添加广告轮播
        FrameLayout adView = (FrameLayout) LayoutInflater.from(getContext()).inflate(R.layout.live_hot_ad, mHotList, false);
        final ViewPager headView = (ViewPager) adView.findViewById(R.id.live_hot_ad_pager);
        final LinearLayout pointGroup = (LinearLayout) adView.findViewById(R.id.point_group);

        //设置广告页内容
        final List<Integer> images = new ArrayList<>();
        images.add(R.drawable.live_hot_ad1);
        images.add(R.drawable.live_hot_ad2);
        images.add(R.drawable.live_hot_ad3);
        images.add(R.drawable.live_hot_ad4);
        PicturePageAdapter pageAdapter = new PicturePageAdapter(getContext(), images);
        headView.setAdapter(pageAdapter);

        // 对ViewPager设置滑动监听
        headView.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            int lastPosition;

            @Override
            public void onPageSelected(int position) {
                // 页面被选中

                // 修改position
                position = position % images.size();

                // 设置当前页面选中
                pointGroup.getChildAt(position).setSelected(true);
                // 设置前一页不选中
                pointGroup.getChildAt(lastPosition).setSelected(false);

                // 替换位置
                lastPosition = position;
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        //设置广告中的圆点
        for (int i = 0; i < images.size(); i++) {
            // 制作底部小圆点
            ImageView pointImage = new ImageView(getContext());
            pointImage.setImageResource(R.drawable.live_hot_ad_point);

            // 设置小圆点的布局参数
            int PointSize = getResources().getDimensionPixelSize(R.dimen.point_size);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(PointSize, PointSize);

            if (i > 0) {
                params.leftMargin = getResources().getDimensionPixelSize(R.dimen.point_margin);
                pointImage.setSelected(false);
            } else {
                pointImage.setSelected(true);
            }
            pointImage.setLayoutParams(params);
            // 添加到容器里
            pointGroup.addView(pointImage);
        }


//        mHandler = new AdHandler(headView);
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                int currentPosition = headView.getCurrentItem();

                if (currentPosition == headView.getAdapter().getCount() - 1) {
                    // 最后一页
                    headView.setCurrentItem(0);
                } else {
                    headView.setCurrentItem(currentPosition + 1);
                }

                // 一直给自己发消息
                mHandler.postDelayed(this, 3000);
            }
        }, 3000);
        //为RecyclerView添加头布局
        mAdapter.addHeadView(adView);
        //监听是否滑动到最下边，到达加载更多数据
        mAdapter.setOnLoadMoreListener(new LiveFragmentAdapter.OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                loadMore();
            }
        });
        mHotList.setAdapter(mAdapter);

        reloadLiveHotList();
        return ret;
    }

//    @Override
//    public void run() {
//        try {
//            while (true) {
//                currentIndex++;
//                if (currentIndex >= 3000) {
//                    currentIndex = 1500;
//                }
//                Message message = mHandler.obtainMessage(998);
//                message.arg1 = currentIndex;
//                mHandler.sendMessage(message);
//                Thread.sleep(5000);
//            }
//        }catch (InterruptedException ex){
//            ex.printStackTrace();
//        }
//    }

    @Override
    public void onDestroyView() {
        Log.d("ddddddddd", "onDestroyView: ");
        super.onDestroyView();
    }

    @Override
    public void onDestroy() {
        Log.d("ddddddddd", "onDestroy: ");
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Override
    public void onDetach() {
        Log.d("ddddddddd", "onDetach: ");
        super.onDetach();
    }

    @Subscribe
    public void onReceiveHotDetail(LiveModel.Data.DataBean.GroupBean dataBean) {
        Toast.makeText(getContext(), "点击了" + dataBean.getTitle(), Toast.LENGTH_SHORT).show();
        Intent intent = new Intent(getContext(), HotDetailActivity.class);
        intent.putExtra("groupBean", dataBean);
        startActivity(intent);
    }

    @Override
    public void onRefresh() {
        if (!checkNet()) {
            Toast.makeText(getContext(), "断网了亲~", Toast.LENGTH_SHORT).show();
            if (mSwipeRefreshLayout.isRefreshing()) {
                mSwipeRefreshLayout.setRefreshing(false);
            }
        } else {
            reloadLiveHotList();
        }

    }

    private void reloadLiveHotList() {
        Observable<LiveModel> observable = mLiveHotService.getLiveModel();
        observable
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.newThread())
                .unsubscribeOn(AndroidSchedulers.mainThread())
                .subscribe(new LiveModelObserver());

    }

    ///////////////////////////////////////////////////////////////////////////
    // 加载数据
    ///////////////////////////////////////////////////////////////////////////

    private class LiveModelObserver implements Observer<LiveModel> {
        @Override
        public void onCompleted() {
            Log.d("ddddddddd", "onCompleted: ");
        }

        @Override
        public void onError(Throwable e) {
            if (mSwipeRefreshLayout.isRefreshing()) {
                mSwipeRefreshLayout.setRefreshing(false);
            }
//            Toast.makeText(getContext(), "加载失败", Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }

        @Override
        public void onNext(LiveModel model) {
            if (mSwipeRefreshLayout.isRefreshing()) {
                mSwipeRefreshLayout.setRefreshing(false);
            }
            String tip = model.getData().getTip();
            Log.d("ddddddd", "call: " + tip);
            mItems.clear();
            List<LiveModel.Data.DataBean> dataBeanList = model.getData().getData();
            mItems.addAll(dataBeanList);
            mAdapter.notifyDataSetChanged();
        }
    }

    ///////////////////////////////////////////////////////////////////////////
    // 加载更多的操作
    ///////////////////////////////////////////////////////////////////////////

    private void loadMore() {
        if (checkNet()) {
            Observable<LiveModel> observable = mLiveHotService.getLiveModel();
            observable
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribeOn(Schedulers.newThread())
                    .unsubscribeOn(AndroidSchedulers.mainThread())
                    .subscribe(new MoreLiveModelObserver());
        } else {
            //没有网络
            Toast.makeText(getContext(), "没有联网", Toast.LENGTH_SHORT).show();
        }
    }


    ///////////////////////////////////////////////////////////////////////////
    // 加载更多的观察者
    ///////////////////////////////////////////////////////////////////////////

    private class MoreLiveModelObserver implements Observer<LiveModel> {
        @Override
        public void onCompleted() {
            Log.d("ddddddddd", "onCompleted: ");

        }

        @Override
        public void onError(Throwable e) {
            if (mSwipeRefreshLayout.isRefreshing()) {
                mSwipeRefreshLayout.setRefreshing(false);
            }
//            Toast.makeText(getContext(), "加载更多失败", Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }

        @Override
        public void onNext(LiveModel model) {
            if (mSwipeRefreshLayout.isRefreshing()) {
                mSwipeRefreshLayout.setRefreshing(false);
            }
            String tip = model.getData().getTip();
            Log.d("ddddddd", "call: " + tip);
            List<LiveModel.Data.DataBean> dataBeanList = model.getData().getData();
            mItems.addAll(dataBeanList);
            mAdapter.notifyDataSetChanged();
        }
    }

}
